package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.mapper.StudentMapper;
import org.example.pojo.PageResult;
import org.example.pojo.Student;
import org.example.pojo.StudentQueryParam;
import org.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 学员列表分页查询
     * @param studentQueryParam
     * @return
     */
    @Override
    public PageResult pageQuery(StudentQueryParam studentQueryParam) {
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());
        Page<Student> page = studentMapper.pageQuery(studentQueryParam);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增学员
     * @param student
     */
    @Transactional
    @Override
    public void insert(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.insert(student);
    }

    /**
     * 根据id查询学员
     * @param id
     * @return
     */
    @Override
    public Student selectById(Integer id) {
        Student student=studentMapper.selectById(id);
        return student;
    }

    /**
     * 修改学员信息
     * @param student
     */
    @Transactional
    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    /**
     * 根据id批量删除学员
     * @param ids
     */
    @Transactional
    @Override
    public void deleteById(List<Integer> ids) {
        studentMapper.deleteByIds(ids);
    }

    /**
     * 添加学员违规信息
     * @param id
     * @param score
     */
    @Transactional
    @Override
    public void addViolation(Integer id, Integer score) {
        Student student=studentMapper.selectById(id);
        student.setViolationCount((short) (student.getViolationCount()+1));
        student.setViolationScore((short) (student.getViolationScore()+score));
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    /**
     * 根据班级id查询学员
     * @param id
     * @return
     */
    @Override
    public List<Student> selectByClazzId(Integer id) {
        return studentMapper.selectByClazzId(id);
    }
}
